package com.clouddot.baipai.ui.fragment.H;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIMainFragmentComponent;
import com.clouddot.baipai.contract.IMainFragmentContract;
import com.clouddot.baipai.http.entity.response.getClassInfoByIdResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoListResponse;
import com.clouddot.baipai.http.entity.response.getCurrentCourseResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.MainFragmentModule;
import com.clouddot.baipai.ui.Dialog.H_ImageDailog;
import com.clouddot.baipai.ui.adapter.V_MainImageAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;
import org.wxy.sdk.util.imageloader.ImageLoaderUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_TWO;
import static com.clouddot.baipai.util.viewUtil.ViewUtil.imageGetter;

/**
 * Created by wxy on 2018/8/23.
 * 横版班牌首页的主页面
 */

public class H_MainFrgment extends BaseFragment implements IMainFragmentContract.IView, View.OnTouchListener {
    //存放班级通知列表的集合
    private List<getClassInfoListResponse.classInfoItem> EntityList = new ArrayList<>();
    //存放班级相册的集合
    private List<getClassInfoListResponse.attachment> imgList = new ArrayList<>();
    //记录当前显示的通知的item
    private int currentNoticeItem;
    //记录当前显示的img的item
    private int currentImgItem;

    private List<ImageView> mItems;
    private V_MainImageAdapter ImageAdapter;
    private boolean isAutoPlay = true; // 图片自动滚动标识
    private boolean isLive = true; //是否还当前的fragment
    private boolean flag = true;


    @Inject
    IMainFragmentContract.IPresenter mPresenter;
    @BindView(R.id.leftLoading)
    ImageView leftLoading;
    @BindView(R.id.loadingLP)
    RelativeLayout loadingLP;
    @BindView(R.id.leftContent)
    ScrollView leftContent;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.tvcontent)
    TextView tvcontent;

    @BindView(R.id.class_photo)
    ViewPager class_photo;

    @BindView(R.id.rightLoading)
    ImageView rightLoading;
    @BindView(R.id.loadingRP)
    RelativeLayout loadingRP;
    @BindView(R.id.right)
    RelativeLayout right;
    @BindView(R.id.lession_name)
    TextView lession_name;
    @BindView(R.id.teacher_photo)
    ImageView teacher_photo;
    @BindView(R.id.teacher_name)
    TextView teacher_name;
    @BindView(R.id.teach_week)
    TextView teach_week;
    @BindView(R.id.teacher_time)
    TextView teacher_time;
    @BindView(R.id.teacher_info)
    LinearLayout teacher_info;


    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_main, null);
    }

    @Override
    protected void initViews() {
        // 采用 dragger2 的架构 -- >
        DaggerIMainFragmentComponent.builder().mainFragmentModule(new MainFragmentModule(this)).build().inject(this);
        ThreadPoolFactory.getThread().execute(new Runnable() {
            @Override
            public void run() {
                mPresenter.getClassInfo(1, "notice", Env.getAppContext().ClassID, 1, 10);
                mPresenter.getClassInfo(2, "image", Env.getAppContext().ClassID, 1, 10);
                mPresenter.getCurrentCourse(Env.getAppContext().ClassID);
            }
        });
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        leftLoading.startAnimation(loadingAnim);
        rightLoading.startAnimation(loadingAnim);
        class_photo.setOnTouchListener(this);
    }

    /**
     * 点击触发的方法 ，对应的ID 对应的逻辑
     * @param view
     */

    @OnClick({
            R.id.img_last, R.id.img_next, R.id.notice_last, R.id.notice_next, R.id.class_photo
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_last:
                if (currentImgItem == 0) {
                    ToastUtil.showToast(getActivity(), "没有上一张了");
                    return;
                }
                class_photo.setCurrentItem(--currentImgItem);

                break;
            case R.id.img_next:
                if (imgList.isEmpty()) return;
                if (currentImgItem >= imgList.size() - 1) {
                    ToastUtil.showToast(getActivity(), "没有下一张了");
                    return;
                }
                class_photo.setCurrentItem(++currentImgItem);
                break;
            case R.id.notice_last:

                if (currentNoticeItem == 0) {
                    ToastUtil.showToast(getActivity(), "没有上一条了");
                    return;
                }
                loadingLP.setVisibility(View.VISIBLE);
                leftContent.setVisibility(View.GONE);
                mPresenter.getClassInfoById(EntityList.get(--currentNoticeItem).Id);
                break;
            case R.id.notice_next:
                if (EntityList.isEmpty()) return;
                if (currentNoticeItem >= EntityList.size() - 1) {
                    ToastUtil.showToast(getActivity(), "没有下一条了");
                    return;
                }
                loadingLP.setVisibility(View.VISIBLE);
                leftContent.setVisibility(View.GONE);
                mPresenter.getClassInfoById(EntityList.get(++currentNoticeItem).Id);
                break;
            case R.id.class_photo:

                break;
        }
    }

    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isLive = true;
            loadingLP.setVisibility(View.VISIBLE);
            leftContent.setVisibility(View.GONE);
            loadingRP.setVisibility(View.VISIBLE);
            right.setVisibility(View.GONE);
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    mPresenter.getClassInfo(1, "notice", Env.getAppContext().ClassID, 1, 10);
                    mPresenter.getClassInfo(2, "image", Env.getAppContext().ClassID, 1, 10);
                    mPresenter.getCurrentCourse(Env.getAppContext().ClassID);
                }
            });
        } else {
            isLive = false;
        }
    }

    @Override
    protected void loadData() {
    }


    /**
     *
     * @param flag 1 --> 获取班级通知的内容
     *             2 --> 获取班级通知和班级相册的列表
     *             3 --> 获取当前正在上课的课程
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refulesClassNoticeInfo(object);
        } else if (flag == 2) {
            refulesClassNoticeAndImage(object);
        } else if (flag == 3) {
            refulesCurrentCourse(object);
        }
    }

    @Override
    public void fail(int flag, String errMsg) {
        if (flag == 1) {
            loadingLP.setVisibility(View.GONE);
            leftContent.setVisibility(View.VISIBLE);
            title.setText(errMsg);
            time.setText("");
            tvcontent.setText("");
        } else if (flag == 2) {
            ToastUtil.showToast(getActivity(), errMsg);
        } else if (flag == 3) {
            loadingRP.setVisibility(View.GONE);
            right.setVisibility(View.VISIBLE);
            lession_name.setText(errMsg);
            teacher_info.setVisibility(View.GONE);
            teacher_photo.setVisibility(View.GONE);
        }
    }


    /**
     * 更新班级通知和班级图片数据
     * @param object
     */
    private void refulesClassNoticeAndImage(Object object) {
        getClassInfoListResponse response = (getClassInfoListResponse) object;
        if (response.flag == 1) {
            if(!response.EntityList.isEmpty()) {
                EntityList = response.EntityList;
                mPresenter.getClassInfoById(response.EntityList.get(0).Id);
            }else{
                loadingLP.setVisibility(View.GONE);
                leftContent.setVisibility(View.VISIBLE);
                title.setText("无班级通知");
                time.setText("");
                tvcontent.setText("");
            }
            currentNoticeItem = 0;

        } else if (response.flag == 2) {
            if(response.EntityList.isEmpty()) {
                imgList.clear();
                getClassInfoListResponse.attachment  a = new getClassInfoListResponse.attachment();
                a.RealPathName = "demo";
                imgList.add(a);
                ToastUtil.showToast(getActivity(), "班级暂时没有图片");

            }else {
                imgList = response.EntityList.get(0).Attachments;
            }

            ImageAdapter = new V_MainImageAdapter(addImageView(imgList), getActivity());
            class_photo.setAdapter(ImageAdapter);
            if (!imgList.isEmpty()) {
                if (flag) {
                    flag = false;
                    ThreadPoolFactory.getThread().execute(startAutoPlay);
                }
            }
            currentImgItem = 0;
        }
    }

    private Runnable startAutoPlay = new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (isLive) handler.sendEmptyMessage(MSG_TWO);
            }
        }
    };

    private List<ImageView> addImageView(List<getClassInfoListResponse.attachment> strings) {
        mItems = new ArrayList<>();
        if (!strings.isEmpty()) {
            for (int i = 0; i < strings.size(); i++) {
                ImageView view0 = new ImageView(getActivity());
                view0.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final H_ImageDailog dailog = new H_ImageDailog(getActivity(), imgList);
                        dailog.showDialog();
                        dailog.getCloseView().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dailog.closeDialog();
                            }
                        });
                    }
                });
                Glide.with(getActivity()).load("http://" + Env.getAppContext().IP + strings.get(i).RealPathName).asBitmap().placeholder(R.drawable.no_cover).error(R.drawable.no_cover).into(view0);
                mItems.add(view0);
            }
        } else {
            ToastUtil.showToast(getActivity(), "班级暂时没有图片");
        }
        return mItems;
    }


    /**
     * 更新班级通知的内容
     * @param object
     */
    private void refulesClassNoticeInfo(Object object) {
        getClassInfoByIdResponse response = (getClassInfoByIdResponse) object;
        title.setText(response.Title);
        time.setText(response.CreateTime);
        if(response.Detail != null && !response.Detail.isEmpty()) {
            final String html = EscapeUnescapeUtil.unescape(response.Detail);
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    final Spanned sp = Html.fromHtml(html, imageGetter, null);
                    Message message = new Message();
                    message.what = MSG_ONE;
                    message.obj = sp;
                    handler.sendMessage(message);
                }
            });
        }
        loadingLP.setVisibility(View.GONE);
        leftContent.setVisibility(View.VISIBLE);
    }

    /**
     * 获取班级正在上课课程
     * @param object
     */
    private void refulesCurrentCourse(Object object) {
        getCurrentCourseResponse response = (getCurrentCourseResponse) object;
        lession_name.setText("正在上课：" + response.CourseName);
        teacher_name.setText(response.TeacherName);
        teach_week.setText("星期 " + getWeekStr(response.WeekNo));
        teacher_time.setText("第 " + getWeekStr(response.ClassNo) + " 节");
        ImageLoaderUtil.getInstance().loadImage("http://" + Env.getAppContext().IP + "", teacher_photo);
        loadingRP.setVisibility(View.GONE);
        teacher_info.setVisibility(View.VISIBLE);
        teacher_photo.setVisibility(View.VISIBLE);
        right.setVisibility(View.VISIBLE);
    }


    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    tvcontent.setText((Spanned) msg.obj);
                    break;
                case MSG_TWO:
                    if (isAutoPlay) {
                        currentImgItem++;
                        currentImgItem = currentImgItem % mItems.size();
                        if (class_photo != null) class_photo.setCurrentItem(currentImgItem);
                    }
                    break;
            }
        }
    };

    private String getWeekStr(String str) {
        if (str.equals("1")) {
            return "一";
        } else if (str.equals("2")) {
            return "二";
        } else if (str.equals("3")) {
            return "三";
        } else if (str.equals("4")) {
            return "四";
        } else if (str.equals("5")) {
            return "五";
        } else if (str.equals("6")) {
            return "六";
        } else if (str.equals("7")) {
            return "七";
        } else if (str.equals("8")) {
            return "八";
        } else if (str.equals("9")) {
            return "九";
        } else if (str.equals("10")) {
            return "十";
        } else {
            return "未知";
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }
}
